package com.zdk.springcloudgateway.config;


import com.zdk.springcloudgateway.common.exception.CustomException;
import com.zdk.springcloudgateway.common.response.ResultCode;
import com.zdk.springcloudgateway.model.Audience;
import com.zdk.springcloudgateway.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * @date 2021/10/11 11:21
 * 拦截token并解析token信息
 */
@Component
@Slf4j
public class JwtInterceptor implements GlobalFilter, Ordered {


    @Autowired
    private Audience audience;


    RedisTemplate<String, String> redisTemplate;

    boolean flag=true;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //拦截方法，拦截到请求后，自动执行
        log.info("filter 拦截方法，拦截到请求后，自动执行 ");

        //获取请求路径
        String path = exchange.getRequest().getPath().toString();

        //获取redis中的过滤列表信息
        String methodPath = redisTemplate.opsForValue().get("Method_Path");

        if (StringUtils.isEmpty(methodPath)){
            throw new CustomException(ResultCode.PARAM_NOT_METHOD_PATH);
        }

        String[] methodPathArray =methodPath.split(",");
        List<String> list=new ArrayList<>();
         Collections.addAll(list,methodPathArray);
        for (String s : list) {
            if (path.startsWith(s)){
                break;
            }
            this.flag=false;
        }
        //如果请求方法在过滤列表种,则放行
        if (flag){
            return chain.filter(exchange);
        }

        String authHeader = exchange.getRequest().getHeaders().getFirst(JwtTokenUtil.AUTH_HEADER_KEY);
        if (StringUtils.isBlank(authHeader) || !authHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
            log.info("### 用户未登录，请先登录 ###");
            throw new CustomException(ResultCode.USER_NOT_LOGGED_IN);
        }

        // 获取token
        final String token = authHeader.substring(7);
        //token失效
        if (JwtTokenUtil.isExpiration(token,audience.getBase64Secret())){
            throw new CustomException(ResultCode.PERMISSION_TOKEN_EXPIRED);
        }
        //获取用户id
        String userId = JwtTokenUtil.getUserId(token, audience.getBase64Secret());

        //将现在的request，添加当前身份
        ServerHttpRequest mutableReq = exchange.getRequest().mutate().header("Authorization-userId", userId).build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        //全部放行
        return chain.filter(mutableExchange);
    }

    @Override
    public int getOrder() {
        //3:系统调用该方法获得过滤器的优先级
        return 1; //数字越小，越优先
    }



}
